<template>
  <div class="cl-upload">
    <div class="upload-opt">
      <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        class="upload-demo"
        name="file"
        :action="action"
        :headers="headers"
        :multiple="multiple"
        :limit="limit"
        :show-file-list="false"
        :on-success="onSuccess"
        :accept="clAccept"
        :data="{
          supplierId: props.supplierId,
          projectId: props.projectId
        }"
        :on-error="onError"
        :on-exceed="onExceed"
      >
        <el-button type="primary" class="upload-btn" plain :disabled="btnDisabled">上传</el-button>
      </el-upload>
    </div>
    <div v-if="showTable" class="upload-table">
      <el-table
        :data="fileList"
        class="cl-table"
        header-cell-class-name="my-header-cell-row"
        cell-class-name="my-cell-row"
      >
        <el-table-column label="序号" type="index" :width="60" fixed="left" />
        <el-table-column prop="name" label="附件名称" />
        <el-table-column prop="percentage" label="上传进度">
          <template #default="{ row }">
            <el-progress v-if="row.percentage" :percentage="row.percentage" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'success'" type="success">上传成功</el-tag>
            <el-tag v-else-if="row.status === 'error'" type="danger">上传失败</el-tag>
            <el-tag v-else type="warning">上传中</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row, $index }">
            <el-button
              v-if="row?.response?.data?.viewPath"
              link
              type="primary"
              class="link-btn"
              @click="onView(row, $index)"
            >
              查看
            </el-button>
            <el-button
              v-if="row?.response?.data?.id"
              link
              type="primary"
              class="link-btn"
              @click="onDownload(row, $index)"
            >
              下载
            </el-button>
            <el-button link type="danger" class="link-btn" @click="onDel(row, $index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { PropType } from 'vue'
import { supplierFileInfoDelete, supplierFileInfoDownload } from '@/api/electronic-bid-file'
const props = defineProps({
  supplierId: {
    type: Number,
    default: null
  },
  projectId: {
    type: Number,
    default: null
  },
  clAccept: {
    type: String,
    default: ''
  },
  initUploadList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  showTable: {
    type: Boolean,
    default: true
  },
  btnDisabled: {
    type: Boolean,
    default: false
  },
  action: {
    type: String,
    default: `${import.meta.env.VITE_APP_BASE_URL_SYH}/cloud/pbgl/supplierFileInfo/uploadFile`
  },
  multiple: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number
  }
})

onMounted(() => {
  init()
})
const init = () => {
  const tempList: any = []
  props.initUploadList.forEach((element) => {
    tempList.push({
      name: element.fileName,
      percentage: 100,
      status: 'success',
      size: element.size,
      uid: element.md5,
      viewPath: element.viewPath,
      downloadPath: element.downloadPath,
      viewButton: element.viewButton,
      response: {
        data: { id: element.id, viewPath: element.viewPath },
        message: {
          code: '200',
          type: '回显数据'
        }
      }
    })
  })
  fileList.value = tempList
}
const onError = (error) => {
  console.log('🐷 🐽 onError 🐽 error👉👉👉', error)
}
const _useBasicStore = useBasicStore()
const headers = ref({
  Authorization: _useBasicStore.token
})
const emit = defineEmits(['on-success-upload', 'on-delete'])
const onSuccess = ({ message, data }, file) => {
  const { code, content } = message
  if (code === '200') {
    elMessage(content)
    emit('on-success-upload', data)
  } else {
    file.status = 'error'
    file.percentage = 0
    elMessage(content, 'error')
  }
}
const onView = (row, index) => {
  if (row.response.data.viewPath) {
    window.open(row.response.data.viewPath)
  } else {
    elMessage('暂无预览', 'error')
  }
}
const onDownload = async (row, index) => {
  try {
    const res = await supplierFileInfoDownload({ id: row.response.data.id })
    downloadFile(row.name, res.data)
  } catch (error) {
    console.log('🐷 🐽 onDownload 🐽 error👉👉👉', error)
  }
}
const onDel = async (row, index) => {
  elConfirmNoCancelBtn('确认框', '确定删除该附件吗？')
    .then(async (res) => {
      if (res === 'confirm') {
        const id = row.response.data?.id
        if (id) {
          await supplierFileInfoDelete({ id })
        }
        fileList.value.splice(index, 1)
        emit('on-delete')
      }
    })
    .catch((e) => {
      console.log('🐷 🐽 elConfirmNoCancelBtn 🐽 e👉👉👉', e)
    })
}
const onExceed = () => {
  elMessage('上传文件数量超过限制', 'error')
}

const fileList = ref<any>([])
// 这边 是额外新增的 文件id
const fileIdList = computed(() => {
  const responseList = fileList.value.map((m) => m.response)
  const ids: any[] = []
  responseList.forEach((m) => {
    // 新上传的文件有 message
    if (m.message) {
      ids.push(Number(m?.data))
    }
  })

  return ids.join()
})
const uploadRef = ref<any>(null)
onBeforeUnmount(() => {
  uploadRef.value.abort()
})
defineExpose({
  fileList,
  fileIdList
})
</script>

<style scoped lang="scss">
.upload-table {
}
.link-btn {
  padding: 0 !important;
}
:deep(.my-header-cell-row) {
  height: 50px;
  font-size: 14px;
  font-family: AlibabaPuHuiTi-Regular;
  font-weight: 400;
  color: #909399;
}

:deep(.my-cell-row) {
  font-size: 14px;
  font-family: AlibabaPuHuiTi-Regular;
  font-weight: 400;
  color: #303133;
}
:deep(.el-upload-list__item-name) {
  font-size: 16px;
  height: 24px;
  .el-upload-list__item-file-name {
    overflow: unset !important;
  }
}
.upload-opt {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.cl-upload {
  width: 100%;
  .icon-title {
    position: relative;
    font-size: 16px;
    font-family: AlibabaPuHuiTi-Regular;
    font-weight: 400;
    color: #434343;
    line-height: 36px;
    margin-left: 10px;
    &::before {
      position: absolute;
      content: '';
      top: 10px;
      left: -10px;
      height: 16px;
      width: 3px;
      background-color: #79bbff;
    }
  }
}
.upload-btn {
  margin-right: 20px;
}
.upload-msg {
  margin: 80px 0 30px 10px;
}
</style>

<style scoped>
@import url('../cl-table/index.scss');
</style>
